import functools
import math

from flask import Blueprint, render_template, request, jsonify, g, session, redirect
from sqlalchemy import and_, or_

from models import db, AdminInfo, UserInfo
from datetime import timedelta, datetime

bg = Blueprint("bg", __name__, url_prefix='/admin')  # 实例化一个蓝图Blueprint对象


# 装饰器验证用户登录
def required_login(view_fun):
    @functools.wraps(view_fun)
    def fun1(*args, **kwargs):
        if 'adminId' not in session:
            return redirect('/login')
        g.adminUser = AdminInfo.query.get(session['adminId'])
        return view_fun(*args, **kwargs)

    return fun1


@bg.route("/login", methods=['GET'])
def tologin():
    return render_template("adminLogin.html")


@bg.route('/login', methods=['POST'])
def login():
    username = request.values.get("username")
    password = request.values.get("password")

    adminUser = AdminInfo.query.filter_by(username=username).first()

    if adminUser:
        if adminUser.password == password:
            # 记录用户登录
            now = datetime.now()
            session['adminId'] = adminUser.id
            session['username'] = adminUser.username
            session['password'] = adminUser.password
            adminUser.update_time = now
            db.session.commit()
            # 返回头像和昵称
            return jsonify(result=200)
        else:
            return jsonify(result=400)  # 密码错误


@bg.route("/index", methods=['GET'])
@required_login
def index():
    return render_template("adminIndex.html")


@bg.route("/home", methods=['GET'])
@required_login
def home():
    return render_template("home.html")


@bg.route("/user", methods=['GET'])
@required_login
def userlist():
    # 获取page参数 默认为1
    page = int(request.args.get('page', 1))
    # 获取每页显示数据条数默认为2
    per_page = int(request.args.get('perpage', 10))

    user_name = request.values.get("username")
    idcard = request.values.get("idcard")
    if user_name is None:
        user_name = ''
    if idcard is None:
        idcard = ''

    filter_list = []
    # 从数据库查询数据
    if user_name is not None or idcard is not None:
        if user_name:
            filter_list.append(UserInfo.user_name.like('%' + user_name + '%'))
        if idcard:
            filter_list.append(UserInfo.id_card == idcard)
        paginates = UserInfo.query.filter(*filter_list).order_by(
            'create_time').paginate(page, per_page, error_out=False)
    else:
        paginates = UserInfo.query.order_by(
            'create_time').paginate(page, per_page, error_out=False)

    stus = paginates.items
    # totalpage为总页面数
    totalpage = math.ceil(paginates.total / per_page)
    return render_template("user-index.html", paginate=paginates, stus=stus, totalpage=totalpage,
                           user_name=user_name,
                           idcard=idcard)


@bg.route("/user/edit", methods=['GET'])
def userEdit():
    id = request.args.get('id')
    if id is None:
        user = UserInfo()
        user.user_name = ''
        user.id_card = ''
        user.mobile = ''
        user.pwd = ''
        return render_template('user-add.html', user=user)
    id = int(id)
    user = UserInfo.query.filter_by(id=id).first()
    return render_template('user-add.html', user=user)


@bg.route("/user/update", methods=['POST'])
def userUpdate():
    id_ = request.values.get('id')
    if id_ == 'None':
        user = UserInfo()
        user.user_name = request.values.get("username")
        user.mobile = request.values.get("phone")
        user.id_card = request.values.get("idcard")
        user.pwd = request.values.get("password")
        user.create_time = datetime.now()
        user.update_time = datetime.now()
        user.isDelete = 'True'
        db.session.add(user)
        db.session.commit()
        return jsonify(result=200)  # 成功

    id = int(id_)
    user = UserInfo.query.filter_by(id=id).first()
    user.user_name = request.values.get("username")
    user.mobile = request.values.get("phone")
    user.id_card = request.values.get("idcard")
    user.pwd = request.values.get("password")
    user.update_time == datetime.now()

    mobile_exists = UserInfo.query.filter(and_(UserInfo.mobile == user.mobile, UserInfo.id != user.id)).count()
    if mobile_exists:
        return jsonify(result=300)  # 手机号存在
    db.session.commit()
    return jsonify(result=200)  # 成功


@bg.route("/user/delete", methods=['POST'])
def userDelete():
    id = int(request.values.get('id'))
    user = UserInfo.query.filter(UserInfo.id == id).first()
    db.session.delete(user)
    db.session.commit()
    return jsonify(result=200)  # 成功


@bg.route('/logout')
def logout():
    session.clear()
    return redirect("/admin/login")
